package com.ruoyi.emergency.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.emergency.domain.EmTask;
import com.ruoyi.emergency.mapper.EmTaskMapper;
import com.ruoyi.emergency.service.IEmTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 应急任务Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-07
 */
@Service
public class EmTaskServiceImpl implements IEmTaskService
{
    @Autowired
    private EmTaskMapper emTaskMapper;

    /**
     * 查询应急任务
     *
     * @param id 应急任务主键
     * @return 应急任务
     */
    @Override
    public EmTask selectEmTaskById(Long id)
    {
        EmTask task = emTaskMapper.selectEmTaskById(id);
        // 逾期判定
        if (task != null && task.getStatus() != null && task.getStatus() != 2 && task.getDeadline() != null) {
            Date now = new Date();
            if (now.after(task.getDeadline())) {
                task.setStatus(3L); // 3=逾期，类型为Long
            }
        }
        return task;
    }

    /**
     * 查询应急任务列表（自动过滤当前用户的任务）
     *
     * @param emTask 应急任务
     * @return 应急任务列表
     */
    @Override
    public List<EmTask> selectEmTaskList(EmTask emTask)
    {
        // 获取当前登录用户ID
        Long currentUserId = SecurityUtils.getUserId();

        // 非管理员只能查看自己负责的任务（假设管理员ID为1，可根据实际调整）
        if (!currentUserId.equals(1L)) {
            // 强制筛选当前用户为责任人的任务
            emTask.setAssigneeId(currentUserId);
        }
        List<EmTask> list = emTaskMapper.selectEmTaskList(emTask);
        Date now = new Date();
        for (EmTask task : list) {
            if (task.getStatus() != null && task.getStatus() != 2 && task.getDeadline() != null && now.after(task.getDeadline())) {
                task.setStatus(3L); // 3=逾期，类型为Long
            }
        }
        return list;
    }

    /**
     * 新增应急任务
     *
     * @param emTask 应急任务
     * @return 结果
     */
    @Override
    public int insertEmTask(EmTask emTask)
    {
        emTask.setCreateTime(DateUtils.getNowDate());
        // 自动填充发布人ID
        emTask.setPublisherId(SecurityUtils.getUserId());
        return emTaskMapper.insertEmTask(emTask);
    }

    /**
     * 修改应急任务
     *
     * @param emTask 应急任务
     * @return 结果
     */
    @Override
    public int updateEmTask(EmTask emTask)
    {
        // 处理任务时自动更新时间（如果是状态变更）
        if (emTask.getStatus() != null) {
            // 若状态改为已完成，自动填充完成时间
            if (emTask.getStatus() == 2) {
                emTask.setFinishTime(DateUtils.getNowDate());
            }
        }
        return emTaskMapper.updateEmTask(emTask);
    }

    /**
     * 批量删除应急任务
     *
     * @param ids 需要删除的应急任务主键
     * @return 结果
     */
    @Override
    public int deleteEmTaskByIds(Long[] ids)
    {
        return emTaskMapper.deleteEmTaskByIds(ids);
    }

    /**
     * 删除应急任务信息
     *
     * @param id 应急任务主键
     * @return 结果
     */
    @Override
    public int deleteEmTaskById(Long id)
    {
        return emTaskMapper.deleteEmTaskById(id);
    }
    @Override
    public void updateTaskStatus(Long taskId, Long status) {
        EmTask task = emTaskMapper.selectEmTaskById(taskId);
        if (task != null) {
            task.setStatus(status);
            if (status == 2L) { // 已完成
                task.setFinishTime(new Date());
            }
            emTaskMapper.updateEmTask(task);
        }
    }

    @Override
    public int countAllTask() {
        return emTaskMapper.countAllTask();
    }

    @Override
    public int countTodayTask() {
        return emTaskMapper.countTodayTask();
    }
    @Override
    public int countTaskByStatus(int status) {
        return emTaskMapper.countTaskByStatus(status);
    }

    @Override
    public int countUserTaskByStatus(Long userId, int status) {
        return emTaskMapper.countUserTaskByStatus(userId, status);
    }

    /**
     * 更新逾期任务状态
     */
    @Override
    public void updateOverdueTasks() {
        emTaskMapper.updateOverdueTasks(new Date());
    }

    @Override
    public List<java.util.Map<String, Object>> getTaskTrend(String startDate, String endDate) {
        // 1. 生成完整日期列表
        List<String> dateList = new java.util.ArrayList<>();
        java.time.LocalDate start = java.time.LocalDate.parse(startDate);
        java.time.LocalDate end = java.time.LocalDate.parse(endDate);
        for (java.time.LocalDate d = start; !d.isAfter(end); d = d.plusDays(1)) {
            dateList.add(String.format("%02d-%02d", d.getMonthValue(), d.getDayOfMonth()));
        }
        // 2. 查询数据库数据
        List<java.util.Map<String, Object>> dbList = emTaskMapper.selectTaskTrend(startDate, endDate);
        java.util.Map<String, java.util.Map<String, Object>> dbMap = new java.util.HashMap<>();
        for (java.util.Map<String, Object> m : dbList) {
            dbMap.put((String)m.get("day"), m);
        }
        // 3. 补全日期，没数据的补0
        List<java.util.Map<String, Object>> result = new java.util.ArrayList<>();
        for (String day : dateList) {
            java.util.Map<String, Object> m = dbMap.getOrDefault(day, null);
            java.util.Map<String, Object> item = new java.util.HashMap<>();
            item.put("day", day);
            item.put("publish", m != null ? m.get("publish") : 0);
            item.put("done", m != null ? m.get("done") : 0);
            item.put("overdue", m != null ? m.get("overdue") : 0);
            result.add(item);
        }
        return result;
    }

    @Override
    public List<java.util.Map<String, Object>> getTaskStatusPie() {
        return emTaskMapper.selectTaskStatusPie();
    }

    @Override
    public List<java.util.Map<String, Object>> getAssigneeRank() {
        return emTaskMapper.selectAssigneeRank();
    }
}